import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/config/config.dart';
import 'package:xvideos/hj_page/mine_business/ai/ai_sub_type/ai_function_Logic.dart';
import 'package:xvideos/hj_page/mine_business/ai/mode/AiModList.dart';
import 'package:xvideos/hj_page/mine_business/ai/widget/pic_selected_view.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_page/user_center_page/widget/gradient_text.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../../hj_model/video_model.dart';
import '../../video/simple_video_player_page.dart';

//ai换脸模版详情页
class AIModDetailPage extends StatelessWidget {
  final TemplateModel modMod;
  const AIModDetailPage(this.modMod, {super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AIChangeFaceDetailModLogic>(
        init: AIChangeFaceDetailModLogic(null, modModel: modMod),
        builder: (controller) {
          return Scaffold(
            appBar: AppBar(
              title: Text(controller.modModel.title ?? ''),
              centerTitle: false,
              titleSpacing: -10,
            ),
            body: Stack(
              children: [
                Column(
                  children: [
                    Expanded(child: _buildContent(controller)),
                    72.sizeBoxH,
                  ],
                ),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    padding: EdgeInsets.fromLTRB(16, 0, 16, 12),
                    child: InkWell(
                      onTap: () => controller.submitAiImage(),
                      child: Container(
                        height: 44,
                        alignment: Alignment.center,
                        margin: EdgeInsets.symmetric(vertical: 12, horizontal: 30),
                        decoration: BoxDecoration(
                          color: AppColors.actionRed,
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: Text(
                          '立即提交',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }

  _buildContent(AIChangeFaceDetailModLogic controller) {
    return SingleChildScrollView(
      padding: EdgeInsets.fromLTRB(16, 12, 16, 60),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              AspectRatio(
                aspectRatio: 343 / 193,
                child: NetworkImageLoader(
                  imageUrl: controller.modModel.cover ?? '',
                  borderRadius: 0,
                  fit: BoxFit.fitWidth,
                ),
              ),
              //视频换脸
              if (controller.isChangeVideo)
                InkWell(
                  onTap: () {
                    VideoModel videoModel = VideoModel()..sourceURL =  controller.modModel.m3u8Url ;
                    Get.to(
                      SimpleVideoPlayerPage(
                        videoUrl: videoModel.realVideoUrl,
                        title: controller.modModel.title ?? '',
                      ),
                    );
                  },
                  child: Image.asset(
                    'circle_play.webp'.videoPath,
                    width: 50,
                  ),
                )
            ],
          ),
          14.sizeBoxH,
          Text(
            "注意事项:",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          8.sizeBoxH,
          Text(
            '''1. 选择一张人脸清晰，不得有任何遮挡的照片上传（注意：只含一个人物和脸部，图片不能过暗）
2. 选择一个心仪的视频或图片模板，点击生成，生成时间需要3-5分钟，耐心等待。（图片模板可自行上传）
3. 在右上角记录查看生成进度，生成成功后可以点击进行下载，也可以在线观看。
4. 按照上方操作，有问题随时联系在线客服进行处理。
5. 不支持多人图片，禁止未成年人图片''',
            style: TextStyle(
              color: Color(0xff989898),
              fontSize: 12,
              height: 18 / 12,
            ),
          ),
          18.sizeBoxH,
          _buildExample(),
          18.sizeBoxH,
          0.5.line,
          18.sizeBoxH,
          Row(
            children: [
              Text(
                "上传脸部信息",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              12.sizeBoxW,
              Text(
                "图片大小请低于2Mb",
                style: TextStyle(
                  color: Color(0xff989898),
                  fontSize: 12,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
          14.sizeBoxH,
          SizedBox(
            width: 120,
            height: 120,
            child: PicSelectedView(
              width: 120,
              height: 120,
              uploadModel: controller.uploadModel,
            ),
          ),
          18.sizeBoxH,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Consumer<GlobalStore>(builder: (_, provider, __) {
                final freeTimes = provider.wallet?.aiUndressFreeTimes ?? 0;
                final presaleCount = presaleProvider.remain?.todayAiUndressCount ?? 0;
                //预售权益和免费次数的和
                final total = freeTimes + presaleCount;
                final hasFreeTimes = total > 0;
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (!controller.isChangeVideo) ...[
                      Text(
                        '你当前免费体验为$total次数',
                        style: TextStyle(
                          color: Color(0xff989898),
                          fontSize: 12,
                        ),
                      ),
                      12.sizeBoxH,
                      Text(
                        '当日免费${provider.wallet?.todayAiFreeTimes}次数',
                        style: TextStyle(
                          color: Color(0xff989898),
                          fontSize: 12,
                        ),
                      ),
                    ],
                    12.sizeBoxH,
                    EasyRichText(
                      '处理一张照片的费用是 ${controller.realCostCoin()}金币',
                      defaultStyle: TextStyle(color: Colors.white.withOpacity(.55), fontSize: 14, fontWeight: FontWeight.w400),
                      patternList: [
                        EasyRichTextPattern(
                          targetString:
                              '${controller.realCostCoin()}金币',
                          style: TextStyle(color: AppColors.actionRed),
                        )
                      ],
                    ),
                    if (controller.isChangeVideo) ...[
                      if (controller.coupon != null) ...[
                        12.sizeBoxH,
                        EasyRichText(
                          '已抵扣 ${controller.coupon?.goodsValue ?? 0}金币',
                          defaultStyle: TextStyle(color: Colors.white.withOpacity(.55), fontSize: 14, fontWeight: FontWeight.w400),
                          patternList: [
                            EasyRichTextPattern(
                              targetString: '${controller.coupon?.goodsValue ?? 0}金币',
                              style: TextStyle(color: AppColors.actionRed),
                            )
                          ],
                        ),
                      ],
                      12.sizeBoxH,
                      Row(
                        children: [
                          if (controller.coupon == null) ...[
                            InkWell(
                              onTap: () => controller.showCoupon(),
                              child: GradientText(
                                '使用抵扣券',
                                colors: [
                                  Color(0xff35DEBC),
                                  Color(0xff22BB9C),
                                ],
                                decoration: TextDecoration.underline,
                                decorationColor: Color(0xff35DEBC),
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                fontSize: 14,
                              ),
                            ),
                          ] else ...[
                            InkWell(
                              onTap: () => controller.showCoupon(),
                              child: GradientText(
                                '更换抵扣券',
                                colors: [
                                  Color(0xff35DEBC),
                                  Color(0xff22BB9C),
                                ],
                                decoration: TextDecoration.underline,
                                decorationColor: Color(0xff35DEBC),
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                fontSize: 14,
                              ),
                            ),
                            12.sizeBoxW,
                            InkWell(
                              onTap: () {
                                //取消优惠券
                                controller.coupon = null;
                                controller.update();
                              },
                              child: Text(
                                '取消',
                                style: textStyle(14, Colors.white.withOpacity(.55), FontWeight.w400),
                              ),
                            )
                          ],
                        ],
                      )
                    ]
                  ],
                );
              })
            ],
          )
        ],
      ),
    );
  }

  _buildExample() {
    return Row(children: [
      _buildExampleItem('正面无遮挡', "ai_changeface_right.webp".aiPath),
      20.sizeBoxW,
      _buildExampleItem('不遮挡脸部', "ai_changeface_wrong_1.webp".aiPath),
      20.sizeBoxW,
      _buildExampleItem('不遮挡眼睛', "ai_changeface_wrong_2.webp".aiPath),
    ]);
  }

  _buildExampleItem(String title, String img) {
    return Expanded(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AspectRatio(
            aspectRatio: 1,
            child: Image.asset(img),
          ),
          14.sizeBoxH,
          Text(
            title,
            style: TextStyle(
              color: Color(0xff989898),
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
}
